package com.example.train_operate.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.train_operate.dto.UserDTO;
import com.example.train_operate.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.train_operate.util.ReidsConstants.LOGIN_CODE_KEY;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        } else {
            String key = LOGIN_CODE_KEY + token;
            Map<Object, Object> entries = this.stringRedisTemplate.opsForHash().entries(key);
            log.info("map:===========>" + entries);
            if (entries.isEmpty()) {
                return true;
            } else {
                User user = BeanUtil.fillBeanWithMap(entries, new User(), false);
                UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class, new String[0]);
                UserHolder.saveUser(userDTO);
                this.stringRedisTemplate.expire(key, ReidsConstants.LOGIN_CODE_TTL, TimeUnit.HOURS);
                return true;
            }
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
